package com.lxf.clouduser.utils;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.lxf.clouduser.bean.RespModel;
import com.lxf.clouduser.bean.UserBean;
import com.lxf.clouduser.bean.UserMsgBean;
import com.lxf.clouduser.mapper.UserItemRepository;
import com.lxf.clouduser.mapper.UserMapper;
import com.lxf.clouduser.mapper.UserMsgItemRepository;
import com.lxf.clouduser.mapper.UserMsgMapper;
import com.lxf.clouduser.netty.NettyConfig;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author 罗兴发
 * @data 2025/6/9 11:15
 * @description：Netty发送消息-工具类
 */
@Component
@Slf4j
public class SendNettyMsgUtils {
    @Resource
    UserMapper userMapper;
    @Resource
    UserMsgMapper userMsgMapper;
    @Resource
    private UserMsgItemRepository userMsgItemRepository;
    @Resource
    private UserItemRepository userItemRepository;

    /**
     * 给单个用户发送消息——公共方法
     * @param msgType
     * @param userId
     * @param msg
     * @return
     */
    public int pushMsgToUser(Integer msgType,String fUserId,String userId,String msg) {
        log.info("用户ID为：{}",userId);
        //发送消息
        Channel channel = NettyConfig.getChannel(userId);
        log.info("通道为：{}",channel);
        if (Objects.isNull(channel)) {
            int i = 0;
            if (i==0){
                log.info("msg","未连接socket服务器");
                //抛出异常
                throw new RuntimeException("未连接socket服务器");
            }
            return i;
        }else {
            try {

                List<UserMsgBean> list = new ArrayList<>();
                //时间规格化
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String addTime = sf.format(new Date());
                //对象实例化
                UserMsgBean userMsg = new UserMsgBean();
                userMsg.setMsgContent(msg);
                userMsg.setFromUserId(fUserId);
                //根据用户ID获取用户头像或名称
                if ("0".equals(fUserId)){
                    userMsg.setFromUserName("系统");
                    userMsg.setFromUserHead("https://q7.itc.cn/q_70/images03/20240925/3077e68dcf2141bea5880fe43f77e625.jpeg");
                }else {
                    UserBean user1 = userItemRepository.findById(fUserId).get();
                    userMsg.setFromUserName(user1.getUserName());
                    userMsg.setFromUserHead(user1.getUserHead());
                }
                userMsg.setToUserId(userId);
                //根据用户ID获取用户头像或名称
                UserBean user2 = userItemRepository.findById(userId).get();
                userMsg.setToUserName(user2.getUserName());
                userMsg.setToUserHead(user2.getUserHead());
                userMsg.setMsgType(msgType);
                userMsg.setGroupId("");
                userMsg.setAddTime(addTime);
                list.add(userMsg);

                //添加消息
                userMsgMapper.addUserMsg(list);
                //es中添加信息
                userMsgItemRepository.save(userMsg);
                //接受消息的list集合
                List<String> bridge = new ArrayList<>();
                bridge.add("0");
                bridge.add(userId);
                //对象实例化
                RespModel respModel = new RespModel();
                respModel.setMsgId(userMsg.getUmId());
                respModel.setUid("");
                respModel.setMsg(msg);
                respModel.setMsgType(msgType);
                respModel.setBridge(bridge);
                //发送消息
                channel.writeAndFlush(new TextWebSocketFrame(new Gson().toJson(respModel)));
                log.info("msg","Msg Send Success");
            }catch (Exception e){
                e.printStackTrace();
                log.info("msg",e.getMessage());
            }
            return 1;
        }
    }

    /**
     * 发公告
     * @param msg
     * @return
     */
    public int pushToAll(String msg) {

        List<UserMsgBean> list = new ArrayList<>();

        //查询所有用户
        List<UserBean> user = userMapper.getUser("0");
        for (UserBean u:user) {
            //时间规格化
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String addTime = sf.format(new Date());
            //对象实例化
            UserMsgBean userMsg = new UserMsgBean();
            userMsg.setMsgContent(msg);
            userMsg.setFromUserId("0");
            //根据用户ID获取用户头像或名称

            userMsg.setToUserName("系统");
            userMsg.setToUserHead("https://q7.itc.cn/q_70/images03/20240925/3077e68dcf2141bea5880fe43f77e625.jpeg");
            userMsg.setToUserId(String.valueOf(u.getUserId()));
            userMsg.setGroupId("");
            userMsg.setMsgType(0);
            userMsg.setAddTime(addTime);
            list.add(userMsg);
            //存储es消息
            userMsgItemRepository.save(userMsg);
        }

        //添加消息
        int i = userMsgMapper.addUserMsg(list);
        if (i>=0){
            for (UserMsgBean m:list) {
                String userId = m.getToUserId();
                //接受消息的list集合
                List<String> bridge = new ArrayList<>();
                bridge.add("0");
                bridge.add(userId);
                //对象实例化
                RespModel respModel = new RespModel();
                respModel.setMsgId(m.getUmId());
                respModel.setUid("");
                respModel.setMsg(msg);
                respModel.setMsgType(0);
                respModel.setBridge(bridge);
                //发送消息
                Channel channel = NettyConfig.getChannel(userId);
                channel.writeAndFlush(new TextWebSocketFrame(new Gson().toJson(respModel)));
            }
            return 1;
        }
        return 0;
    }

}
